<template>
  <div>
    <Modal
      v-model="showCtfQuicklyConfig"
      title="快速构建"
      width="1200px"
      class="wide"
      :mask-closable="false"
      @on-visible-change="visibleChange"
    >
      <Form
        ref="quickCreatForm"
        :model="quickCreatForm"
        :label-width="80"
        :rules="ruleQuickCreatForm"
      >
        <!-- ctf线上模式不要备用环境套数 -->
        <FormItem
          v-if="!ctfVpn"
          label="备用环境数："
          prop="spareEnvNum"
          style="font-weight: bold;text-align:left;"
          id="envNum"
        >
          <InputNumber :min="0" :max="1000" v-model="quickCreatForm.spareEnvNum" placeholder="1" />
          <span style="color:#f90">
            <Icon type="ios-information-circle-outline" />
            建议备用环境的套数为实际参赛团队的1/3,备用环境的套数不能超过团队总数
          </span>
        </FormItem>
        <!-- <FormItem> -->
        <template v-if="onlineMode == 0 || ctfVpn">
          <div style="font-weight: bold;" v-if="!ctfVpn">
            允许实物接入:
            <i-switch
              v-model="quickCreatForm.pmInEnable"
              :disabled="type === 9"
              :before-change="() => handleBeforeChange(quickCreatForm.pmInEnable, 'pm')"
            />
            <span style="color:#f90">
              <Icon type="ios-information-circle-outline" /> 用于选手通过笔记本接入到竞赛环境{{
                type === 9 ? '（运维赛必须允许实物接入，不可切换）' : ''
              }}
            </span>
          </div>
          <div
            style="font-weight: bold;margin:20px 0"
            v-if="!(type === 2 && onlineMode == 0 && envType === 0)"
          >
            允许虚拟接入:
            <i-switch
              v-model="quickCreatForm.vmInEnable"
              :disabled="type === 9"
              :before-change="() => handleBeforeChange(quickCreatForm.vmInEnable, 'vm')"
              @on-change="vmTeamOrPerson = 'team'"
            />
            <span style="color:#f90">
              <Icon type="ios-information-circle-outline" />
              用于选手通过虚拟机作为跳板，访问竞赛环境中的题目{{
                type === 9 ? '（运维赛必须允许虚拟接入，不可切换）' : ''
              }}
            </span>
          </div>
          <!-- 选择 按团队分配还是按成员分配 -->
          <div style="font-weight: bold;margin:20px 0" v-if="quickCreatForm.vmInEnable">
            接入机器分配方式：
            <RadioGroup v-model="vmTeamOrPerson">
              <Radio label="team">按团队分配</Radio>
              <Radio label="person">按成员分配</Radio>
            </RadioGroup>
          </div>
        </template>
        <template v-if="type === 1">
          <div style="font-weight: bold;margin:20px 0">
            是否有Flag服务器:
            <i-switch v-model="hasFlagServer" />
            <span style="color:#f90">
              <Icon type="ios-information-circle-outline" /> 是否在Topo图中添加Flag服务器
            </span>
          </div>
        </template>
        <!-- <template v-if="type === 2">
					<div style="font-weight: bold;margin:20px 0">
						部署策略:
						<i-switch v-model="deploymentType" size="large" class="deployment-switch">
							<span slot="open">分批构建</span>
							<span slot="close">默认部署</span>
						</i-switch>
						<span style="color:#f90" v-show="!deploymentType">
							<Icon type="ios-information-circle-outline" /> 默认部署时，会同时部署、启动所有虚拟机，资源占用较大，推荐在资源充足时使用
						</span>
						<span style="color:#f90" v-show="deploymentType">
							<Icon type="ios-information-circle-outline" /> 分批构建时，会在部署完成后将虚拟机关机，资源占用较小，推荐在资源紧张时使用
						</span>
					</div>
					<div style="font-weight: bold;margin:20px 0" v-if="deploymentType">
						批次大小：
						<InputNumber :min="1" :max="maxScope"
							v-model="quickCreatForm.batchDeploySize" :placeholder="scope"/>
						<span style="color:#f90"> 
							<Icon type="ios-information-circle-outline" /> 批次大小设置的最大值不得超过竞赛环境套数（包含备用环境）* 有环境的题目数：{{scope}}
						</span>
					</div>
				</template> -->
        <section class="sel-team">
          <h4>
            已选团队
            <Tag color="purple">{{ teamList.length }}</Tag>
            <span class="error-text">{{
              noTeam
                ? '所选团队不能为空'
                : showDuplicateNameTip
                ? `${repeatTeam.join(',')}中存在相同成员`
                : ''
            }}</span>
          </h4>
          <section style="margin:10px 0; display: flow-root;">
            <Tag
              class="sel-team-tag"
              v-for="item in teamList"
              :key="item.id"
              :name="item.name"
              closable
              :color="item.color || 'primary'"
              @on-close="removeTeam([], item)"
              type="dot"
              >{{ item.name }}</Tag
            >
          </section>
          <div class="team-list">
            <Row>
              <Col span="24" style="margin-top: 20px">
                <Select filterable
                  v-if="isDistributed == 1"
                  style="width: 200px;"
                  v-model="rangeIdGroup"
                  placeholder="请选择靶场"
                  @on-change="changeRangeGroup"
                  :not-found-text="loadingRange ? '加载中...' : '无匹配数据'"
                  label-in-value
                  filterable
                  class="experimental-group"
                >
                  <Option
                    v-for="range in rangeList"
                    :title="range.name"
                    :value="range.id"
                    :key="range.id"
                    :label="range.name"
                    >{{ range.name }}</Option
                  >
                </Select>
                <Input
                  v-model.trim="teamListObj.name"
                  placeholder="团队名称"
                  style="width: 200px;"
                  clearable
                  @on-change="queryTeamList"
                />
              </Col>
            </Row>
            <Table
              border
              :columns="teamsCol"
              :data="teamsDataPage"
              class="mtb"
              :loading="loadingTable"
              @on-select-all="selectTeam"
              @on-select="selectTeam"
              @on-select-all-cancel="removeTeam"
              @on-select-cancel="removeTeam"
            >
            </Table>
            <Page
              :total="teamsTotal"
              show-total
              show-elevator
              show-sizer
              :page-size="teamListObj.pageSize"
              :current="teamListObj.pageIndex"
              @on-page-size-change="teamsChangeSize"
              @on-change="teamsPageNum"
              style="float: right"
            />
          </div>
        </section>
        <section class="sel-ques">
          <h4>
            已选题目
            <Tag color="purple">{{ challList.length }}</Tag>
          </h4>
          <section style="margin:10px 0; display: inline-block; width: 100%;">
            <Tag
              class="sel-ques-tag"
              v-for="item in challList"
              :key="item.chaId"
              :name="item.chaName"
              closable
              color="primary"
              type="dot"
              @on-close="removeQuestion([], item)"
              >{{ item.chaName }}
              {{ ctfVpn ? (item.circumstance === 'share' ? '-共享环境' : '-独享环境') : '' }}</Tag
            >
          </section>
          <Row class="search-criteria-row">
            <Col span="24">
              <Select filterable
                style="width: 200px;"
                v-model="rangeId"
                v-if="isDistributed == 1"
                placeholder="请选择靶场"
                @on-change="changeRange"
                :not-found-text="loadingRange ? '加载中...' : '无匹配数据'"
                label-in-value
                filterable
                class="experimental-group"
              >
                <Option
                  v-for="range in rangeList"
                  :title="range.name"
                  :value="range.id"
                  :key="range.id"
                  :label="range.name"
                  >{{ range.name }}</Option
                >
              </Select>
              <Input
                v-model.trim="ctfListObj.name"
                placeholder="题目名称"
                style="width: 200px;"
                clearable
                @on-change="queryChallsList"
                class="mr16"
              />
              <Input
                v-model.trim="ctfListObj.imageName"
                v-if="type === 8"
                placeholder="镜像名称"
                style="width: 200px;"
                clearable
                @on-change="queryChallsList"
                class="mr16"
              />
              <Select filterable
                v-model="ctfListObj.needEnv"
                style="width: 200px;"
                @on-change="queryChallsList"
                v-if="[2, 9].includes(type) && envType === 1"
              >
                <Option value="all">全部(是否需要环境)</Option>
                <Option value="true">需要</Option>
                <Option value="false">不需要</Option>
              </Select>
              <Select filterable
                v-model="ctfListObj.category"
                v-if="type !== 8"
                style="width:150px;margin-left: 2px"
                placeholder="类型"
                @on-change="queryChallsList()"
              >
                <Option value="all">全部(题目类型)</Option>
                <Option
                  :value="category.dictname"
                  v-for="category in questionTypeList"
                  :key="category.dictname"
                  :title="category.dictname"
                  >{{ category.dictname }}</Option
                >
              </Select>
              <Select filterable
                v-model="ctfListObj.flagType"
                style="width: 200px;"
                @on-change="queryChallsList"
                v-if="[2, 8, 9].includes(type)"
              >
                <Option value="all">全部(验证类型)</Option>
                <Option value="1">静态Flag</Option>
                <Option value="0">固定Flag</Option>
                <Option value="2" v-if="type === 9">Checker</Option>
                <Option value="3" v-if="type !== 8">提交报告</Option>
              </Select>
            </Col>
          </Row>
          <Alert type="warning" show-icon v-if="type === 8" class="mtb">
            <p style="color:#f90">攻防赛plus中，使用相同镜像的题目，只会部署一台虚拟机</p>
          </Alert>
          <Table
            border
            :columns="challsCol"
            :data="challsDataPage"
            class="mtb"
            @on-select-all="selectQuestion"
            @on-select="selectQuestion"
            @on-select-all-cancel="removeQuestion"
            @on-select-cancel="removeQuestion"
          ></Table>
          <Page
            :total="challsTotal"
            show-total
            show-elevator
            show-sizer
            :page-size="ctfSearch.pageSize"
            :current="ctfSearch.pageIndex"
            @on-page-size-change="challsChangeSize"
            @on-change="challsPageNum"
            style="text-align: right"
          />
        </section>
      </Form>
      <div slot="footer">
        <Button type="text" @click="closeModal">取消</Button>
        <template
          v-if="
            challWithEnvList.length === 0 &&
              quickCreatForm.vmInEnable &&
              teamList.length > 0 &&
              challList.length > 0
          "
        >
          <Poptip
            confirm
            title="所选的题目都是没环境的题目，如果依然选择虚拟接入的方式，可能在应用中没有实际意义，确定继续？"
            @on-ok="saveQuickCreate('quickCreatForm')"
            :disabled="saveLoading"
            class="text-left"
          >
            <Button type="primary" :loading="saveLoading">确定</Button>
          </Poptip>
        </template>
        <template v-else>
          <Button type="primary" @click="saveQuickCreate('quickCreatForm')" :loading="saveLoading"
            >确定</Button
          >
        </template>
      </div>
    </Modal>
  </div>
</template>

<script>
// import { getAllRanges } from '@/api/access_new'
import { queryCtfList } from '@/api/question'
import { getGroupHasUsers } from '@/api/company'
import { queryExperGroups, getExperGroupsUsers } from '@/api/users'
import {
  quickCreateContest,
  quickCreateContestMacth,
  saveCtfPaper,
  saveCtfPaperNew,
  modifyScene,
  batchAddTarget
} from '@/api/drill_compete'
import { experType } from '@/api/dict'
import { encode } from '@/libs/utils'

export default {
  name: 'quickCreate',
  props: {
    type: {
      // 快速构建
      type: Number,
      default: 2
    },
    extension: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isDistributed: 0,
      scriptModal: false,
      scriptTitle: '',
      hasFlagServer: false,
      saveLoading: false,
      questionTypeList: [], // 题目类型
      deploymentType: false, // 部署策略
      showCtfQuicklyConfig: false,
      title: '',
      noTeam: false,
      quickCreatForm: {
        spareEnvNum: 1,
        batchDeploySize: 1,
        vmInEnable: true,
        pmInEnable: true
      },
      vmTeamOrPerson: 'team',
      ruleQuickCreatForm: {
        batchDeploySize: [
          { required: true, trigger: 'change', message: '不能为空', type: 'number' },
          { validator: this.batchDeploySizeValidator, trigger: 'change' }
        ],
        spareEnvNum: [{ validator: this.spareEnvNumValidator, trigger: 'change' }]
      },
      //ctf题目数据
      ctfSearch: {
        pageIndex: 1,
        pageSize: 10
      },
      ctfListObj: {
        matchMode: '2',
        imageName: '',
        name: '',
        needEnv: 'all',
        flagType: 'all',
        category: 'all',
        rangeId: ''
      },
      challsDataPage: [],
      challsTotal: 0,
      challsCol: [
        {
          type: 'selection',
          width: 60,
          align: 'left'
        },
        {
          title: '题目名称',
          key: 'name',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },

        {
          title: '题目类型',
          key: 'category',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '验证类型',
          key: 'flagType',
          align: 'left',
          render: (h, params) => {
            return h('span', this.$options.filters.filterFlagType(params.row.flagType))
          }
        },
        {
          title: '是否需要部署',
          key: 'needEnv',
          align: 'left',
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  color: params.row.imageId ? 'green' : 'red'
                }
              },
              params.row.imageId ? '需要' : '不需要'
            )
          }
        },
        {
          title: '题目分数',
          key: 'score',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '描述',
          key: 'description',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },
        // {
        //   title: '来源靶场',
        //   key: 'rangeName',
        //   align: 'left',
        //   ellipsis: true,
        //   tooltip: true
        // },
        {
          title: '操作',
          key: 'os',
          align: 'left',
          ellipsis: true,
          width: 180,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    // 非运维赛不允许选择安全运维类型的赛题
                    disabled:
                      this.challList.map((cha) => cha.chaId).includes(params.row.chaId) ||
                      (this.type !== 9 && params.row.category === '安全运维') ||
                      (this.type !== 2 && params.row.answers.length > 1) ||
                      params.row._disabled
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.selectQuestion('', params.row)
                    }
                  }
                },
                '添加'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    // 非运维赛不允许选择安全运维类型的赛题
                    disabled:
                      (this.type !== 9 && params.row.category === '安全运维') ||
                      (this.type !== 2 && params.row.answers.length > 1) ||
                      params.row._disabled ||
                      !params.row.imageId ||
                      params.row.circumstance === 'share'
                  },
                  style: {
                    marginRight: '5px',
                    display: this.ctfVpn ? '' : 'none'
                  },
                  on: {
                    click: () => {
                      this.changeCircumstance('share', params.row)
                    }
                  }
                },
                '共享'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    // 非运维赛不允许选择安全运维类型的赛题
                    disabled:
                      (this.type !== 9 && params.row.category === '安全运维') ||
                      (this.type !== 2 && params.row.answers.length > 1) ||
                      params.row._disabled ||
                      !params.row.imageId ||
                      params.row.circumstance === 'private'
                  },
                  style: {
                    marginRight: '5px',
                    display: this.ctfVpn ? '' : 'none'
                  },
                  on: {
                    click: () => {
                      this.changeCircumstance('private', params.row)
                    }
                  }
                },
                '独享'
              )
            ])
          }
        }
      ],
      challList: [], //选择的题目
      challWithEnvList: [], //选择题目中包含环境的
      //团队表格数据
      teamListObj: {
        pageIndex: 1,
        pageSize: 10,
        visibility: 'all',
        name: '',
        order: 'desc',
        sortBy: 'created'
      },
      teamsTotal: 0,
      teamsDataPage: [],
      teamsCol: [
        {
          type: 'selection',
          width: 60,
          align: 'left'
        },
        {
          title: '团队名称',
          key: 'name',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '团队成员数',
          key: 'userNum',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '团队成员',
          key: 'userList',
          align: 'left',
          ellipsis: true,
          render: (h, params) => {
            return h(
              'Tooltip',
              {
                props: {
                  'max-width': '300',
                  transfer: true,
                  content: params.row.userList
                },
                style: {
                  width: '100%'
                }
              },
              [
                h(
                  'span',
                  {
                    style: {
                      display: 'block',
                      width: '100%',
                      overflow: 'hidden',
                      'text-overflow': 'ellipsis'
                    }
                  },
                  params.row.userList
                )
              ]
            )
          }
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'left',
          ellipsis: true,
          tooltip: true
        },
        // {
        //   title: '来源靶场',
        //   key: 'rangeName',
        //   align: 'left',
        //   ellipsis: true,
        //   tooltip: true
        // },
        {
          title: '操作',
          key: 'os',
          align: 'left',
          ellipsis: true,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    disabled:
                      this.teamList.map((team) => team.id).includes(params.row.id) ||
                      params.row.userIdList.length === 0
                  },
                  on: {
                    click: () => {
                      this.selectTeam('', params.row)
                    }
                  }
                },
                '添加'
              )
            ])
          }
        }
      ],
      teamList: [],
      quickCreatPass: {}, //从父组件传入的参数
      //快速构建传参
      sceneOptions: {
        vmInEnable: true,
        pmInEnable: true,
        autoStandbyEnable: false,
        contestId: '',
        contestName: '',
        contestPapers: [
          {
            flavorRef: '',
            imageRef: '',
            name: ''
          }
        ],
        dataChannelEnable: false,
        matchMode: this.type,
        partyEnable: false,
        spareEnvNum: 1,
        teams: [
          {
            addUserEnable: false,
            id: '',
            name: '',
            partyId: '',
            userIds: []
          }
        ],
        type: 0,
        userNum: 0
      },
      onlineMode: 0,
      showDuplicateNameTip: false,
      repeatTeam: [],
      rangeList: [],
      rangeIdGroup: '',
      rangeId: '',
      loadingRange: false,
      selfRange: '', //本靶场
      loadingTable: false,
      envType: 1
    }
  },
  computed: {
    vmImageDictionaries() {
      let ret = {}
      this.challWithEnvList.forEach((item) => {
        ret[item.imageRef] = item.chaId
      })
      return ret
    },
    scope() {
      // 计算显示批次大小应该展示的设值范围
      if (this.challWithEnvList.length) {
        return `1~${this.maxScope}`
      } else {
        return '0~0'
      }
    },
    maxScope() {
      // 通过团队数、备用环境数、环境内有环境的题目数，计算批次大小最大设置值
      let needEnvQuestionNum = this.challWithEnvList.length || 0
      let teamNum = this.teamList.length || 0
      let spareEnvNum = this.quickCreatForm.spareEnvNum || 0
      return needEnvQuestionNum * (teamNum + spareEnvNum)
    },
    ctfVpn() {
      if (!this.quickCreatPass.extensionObj) {
        return
      }
      let { onlineMode, vpn } = this.quickCreatPass.extensionObj
      let ctfVpn = this.type === 2 && onlineMode && vpn //ctf线上vpn
      return ctfVpn
    }
  },
  watch: {
    deploymentType(newValue) {
      // 修改是否是分批部署的状态时，选择默认部署时将分批部署的数量设置为空
      this.quickCreatForm.batchDeploySize = newValue ? 1 : undefined
    },
    teamList(list) {
      // 选中的团队改变时，存在重复用户，需要查出是哪些团队存在重复信息
      if (this.showDuplicateNameTip) {
        let retList = []
        list.forEach((team, index) => {
          // 双层遍历，将有重复用户的团队查找出来
          for (let i = index + 1, length = list.length; i < length; i++) {
            let userIds = team.userIds
            let nextUserIds = list[i].userIds
            if (
              [...new Set(userIds.concat(nextUserIds))].length !==
              userIds.length + nextUserIds.length
            ) {
              // 去重后长度不等，则数据有重复
              retList.push(`${team.name}`, `${list[i].name}`)
            }
          }
        })
        this.repeatTeam = [...new Set(retList)]
        list.forEach((item) => {
          item.color = this.repeatTeam.includes(item.name) ? 'error' : 'primary'
        })
      } else {
        list.forEach((item) => (item.color = 'primary'))
      }
      this.noTeam = list.length === 0
    }
  },
  filters: {
    // 格式化状态码转换
    filterFlagType(type) {
      if (type == 0) {
        return '固定Flag'
      } else if (type == 1) {
        return '静态Flag'
      } else if (type == 2) {
        return 'Checker'
      } else if (type == 3) {
        return '提交报告'
      } else {
        return '未定义类型'
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getQuestionType()
      if (this.type === 8) {
        let index = this.challsCol.findIndex((item) => item.title === '是否需要部署')
        if (index !== -1) {
          this.challsCol.splice(index, 1, {
            title: '镜像名称',
            key: 'imageName',
            align: 'left',
            tooltip: true
          })
        }
        index = this.challsCol.findIndex((item) => item.title === '操作')
        if (index !== -1) {
          this.challsCol.splice(index, 1, {
            title: '操作',
            key: 'os',
            align: 'left',
            ellipsis: true,
            width: 145,
            render: (h, params) => {
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'primary',
                      size: 'small',
                      // 非运维赛不允许选择安全运维类型的赛题
                      disabled:
                        this.challList.map((cha) => cha.chaId).includes(params.row.chaId) ||
                        (this.type !== 9 && params.row.category === '安全运维') ||
                        (this.type !== 2 && params.row.answers.length > 1)
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        this.selectQuestion('', params.row)
                      }
                    }
                  },
                  '添加'
                )
              ])
            }
          })
        }
      }
    })
  },
  methods: {
    // 题目共享独享切换
    changeCircumstance(type, data) {
      data.circumstance = type
      let dataIndex = this.challsDataPage.findIndex((ques) => ques.id === data.id)
      if (dataIndex !== -1) {
        this.challsDataPage[dataIndex].circumstance = type
      }
      let selIndex = this.challList.findIndex((ques) => ques.chaId === data.id)
      if (selIndex !== -1) {
        this.challList[selIndex].circumstance = type
      }
      let selEnvIndex = this.challWithEnvList.findIndex((ques) => ques.chaId === data.id)
      if (selEnvIndex !== -1) {
        this.challWithEnvList[selEnvIndex].circumstance = type
      }
    },
    changeRangeGroup(range) {
      let exprange = {
        name: range.label,
        id: range.value
      }
      this.teamListObj.pageIndex = 1
      this.rangeIdGroup = exprange.id
      this.getAllTeamlist(exprange.id)
    },
    //题目选择靶场
    changeRange(range) {
      let exprange = {
        name: range.label,
        id: range.value
      }
      this.ctfSearch.pageIndex = 1
      this.rangeId = exprange.id
      this.getAllCtflist(exprange.id)
    },
    // getAllRanges(type) {
    //   this.loadingRange = true
    //   getAllRanges()
    //     .then((res) => {
    //       if (res.code == 1) {
    //         this.rangeList = res.data.items
    //         this.selfRange = this.rangeList.find((item) => {
    //           if (item.self == '0') {
    //             return item
    //           }
    //         })
    //         if (type == 0) {
    //           this.rangeList = []
    //           this.rangeList.push(this.selfRange)
    //         }
    //         this.rangeId = this.rangeList[0].id
    //         this.rangeIdGroup = this.rangeList[0].id
    //         // this.getExpGroupList(this.rangeId);
    //         this.getAllTeamlist(this.rangeIdGroup)
    //         this.getAllCtflist(this.rangeId)
    //       } else {
    //         this.$Message.warning('查询靶场失败')
    //       }
    //     })
    //     .finally(() => {
    //       this.loadingRange = false
    //     })
    // },
    // 获取题目类型
    getQuestionType() {
      experType('questionType')
        .then(({ code, message, attribute = [] }) => {
          if (code !== 1) {
            this.$Message.warning(message)
          } else {
            this.questionTypeList = ((attribute.attribute[0] || {}).dictEntryList || []).map(
              (item) => {
                return {
                  dictname: unescape(item.dictname)
                }
              }
            )
          }
        })
        .catch(() => {
          this.$Message.error('获取题目类型异常')
        })
    },
    // 校验分批部署批次大小设置是否合理，最大设置数通过选中的有环境的题目动态获取
    batchDeploySizeValidator(rule, value, callback) {
      if (value) {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数'))
        } else {
          if (value < 1 || value > this.challWithEnvList.length) {
            callback(new Error('设置超出范围'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('不能为空'))
      }
    },
    spareEnvNumValidator(rule, value, callback) {
      if (value || value === 0) {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数'))
        } else {
          if (value < 0 || value > 1000) {
            callback(new Error('设置超出范围'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('不能为空'))
      }
    },
    // 打开Modal，初始化数据
    openQuickModal(params) {
      this.showCtfQuicklyConfig = true
      this.vmTeamOrPerson = 'team'
      this.title = params.row.name
      //线上线下模式
      let extension
      try {
        extension = JSON.parse(params.row.extension)
      } catch (e) {
        extension = {}
      }
      this.isDistributed = extension.isDistributed
      console.log(extension)
      this.getAllTeamlist(this.rangeIdGroup)
      this.getAllCtflist(this.rangeId)
      // 没有分布式
      // console.log(this.isDistributed, 'this.isDistributedthis.isDistributed')
      // if (extension.isDistributed != 1) {
      //   let type = 0
      //   this.getAllRanges(type)
      // } else {
      //   let type = 1
      //   this.getAllRanges(type)
      // }
      this.onlineMode = extension.onlineMode || 0
      if (this.onlineMode == 1) {
        // 线上赛这两个参数默认为false
        this.quickCreatForm.pmInEnable = false
        this.quickCreatForm.vmInEnable = false
      }
      this.envType = extension.envType === 0 ? 0 : 1 //默认独享
      if (this.type === 2) {
        //共享环境，ctf线下
        if (this.envType === 0) {
          this.quickCreatForm.vmInEnable = false
        }
        let { onlineMode, vpn } = extension
        if (onlineMode === 1 && vpn) {
          this.quickCreatForm.spareEnvNum = 0
        }
      }
      this.teamListObj = {
        pageIndex: 1,
        pageSize: 10,
        visibility: 'all',
        name: '',
        order: 'desc',
        sortBy: 'created'
      }
      this.ctfSearch = {
        pageIndex: 1,
        pageSize: 10
      }
      this.ctfListObj = {
        matchMode: [2, 8, 9].includes(this.type) ? '' : '1', // 夺旗赛不设置搜索条件，攻防赛需要查询只适用于攻防赛的题目
        name: '',
        imageName: '',
        needEnv: this.type === 2 && this.envType === 0 ? 'false' : 'all',
        flagType: 'all',
        category: 'all',
        rangeId: ''
      }
      this.teamList = []
      this.challList = []
      this.challWithEnvList = []
      //将传入过来的部分参数保存
      this.quickCreatPass = { ...params.row, extensionObj: extension }
      this.$refs.quickCreatForm.resetFields()
      // this.getAllTeamlist();
    },
    // 获取设计师可以查看的题目
    getAllCtflist(rangeId) {
      let _this = this
      let params = JSON.parse(JSON.stringify(_this.ctfListObj))
      params.rangeId = rangeId
      params.needEnv = [2, 9].includes(this.type)
        ? _this.ctfListObj.needEnv === 'all'
          ? ''
          : _this.ctfListObj.needEnv
        : 'true'
      params.category = _this.ctfListObj.category === 'all' ? '' : _this.ctfListObj.category
      params.flagType = [2, 8, 9].includes(this.type)
        ? _this.ctfListObj.flagType === 'all'
          ? ''
          : _this.ctfListObj.flagType
        : '1'
      params.applicationList = [0, 2] //竞赛和通用
      if (this.type === 8) {
        // 攻防赛plus不查询checke、报告类型的赛题
        params.matchMode = '4'
      } else if (this.type === 2) {
        // 夺旗赛不查询Checker类型的赛题
        params.otherFlagType = '2'
      } else {
        delete params.otherFlagType
      }
      queryCtfList(params, this.ctfSearch).then((data) => {
        if (data.code == 1) {
          //新接口查询主观题原chaId变为id，needEnv字段查询时候需要，但返回无此字段用是否有镜像代替是否需要环境。保持页面原有逻辑
          data.data.items.forEach((item) => {
            // 非运维赛不允许选择安全运维类型的赛题; 非夺旗赛不允许选择多flag的题目
            item._disabled =
              (this.type !== 9 && item.category === '安全运维') ||
              (this.type !== 2 && item.answers.length > 1)
            item.chaId = item.id
            if (item.imageId) {
              item.needEnv = 'true'
            } else {
              item.needEnv = 'false'
            }
            if (item.matchMode === '3') {
              //竞赛演练禁止选择问答题
              item._disabled = true
            }
          })

          let list = []
          if (data.data.items) {
            list = data.data.items
          }
          let selQuesIds = this.challList.map((team) => team.chaId)
          list.forEach((ques) => {
            // 选中已添加的题目
            if (selQuesIds.includes(ques.chaId)) {
              ques._checked = true
            } else {
              ques._checked = false
            }
            if (this.type === 2) {
              let { onlineMode, vpn } = this.quickCreatPass.extensionObj
              if (onlineMode && vpn && ques.needEnv === 'true') {
                //题目默认设置成独享环境
                let selQues = this.challList.find((selQues) => selQues.chaId === ques.id)
                ques.circumstance = selQues ? selQues.circumstance : 'private'
              }
            }
          })
          if (this.type === 8) {
            list.forEach((ques) => {
              // 存在于词典中的数据，需要被自动选中
              if (this.vmImageDictionaries[ques.imageId] === ques.id) {
                ques.__needEnv = true
              }
            })
          }
          this.challsDataPage = list
          this.challsTotal = Number(data.data.total)
        }
      })
    },
    // 使用指定分页大小查询当前页的题目列表
    challsChangeSize(page) {
      this.ctfSearch.pageSize = page
      this.getAllCtflist(this.rangeId)
    },
    // 查询指定页的题目列表
    challsPageNum(val) {
      this.ctfSearch.pageIndex = val
      this.getAllCtflist(this.rangeId)
    },
    // 查询首页题目列表
    queryChallsList() {
      this.ctfSearch.pageIndex = 1
      this.getAllCtflist(this.rangeId)
    },
    // 选择题目并添加
    selectQuestion(selection, row) {
      let questionList = []
      if (!row) {
        // 全选
        selection.forEach((ques) => {
          let selQuesIds = this.challList.map((team) => team.chaId)
          if (!selQuesIds.includes(ques.chaId)) {
            // 添加不包含的题目
            let listQues = this.challsDataPage.filter((chall) => chall.chaId == ques.chaId)
            if (listQues.length > 0) {
              listQues[0]._checked = true
            }
            questionList.push({ row: ques })
          }
        })
      } else {
        let listQues = this.challsDataPage.filter((chall) => chall.chaId == row.chaId)
        if (listQues.length > 0) {
          listQues[0]._checked = true
          questionList.push({ row })
        }
      }
      // 遍历后一次赋值
      let challList = [],
        challWithEnvList = []
      // 遍历查询当前选中的题目关联的镜像是否已需要部署，还未部署的首个题目将是否需要选中的状态设置为选中
      let vmImageList = Object.keys(this.vmImageDictionaries)
      questionList.forEach((item) => {
        if (!vmImageList.includes(item.row.imageId)) {
          vmImageList.push(item.row.imageId)
          this.$set(item.row, '__needEnv', true)
          this.challsDataPage.forEach((subItem) => {
            if (subItem.chaId === item.row.chaId) {
              this.$set(subItem, '__needEnv', true)
            }
          })
        }
      })
      questionList.forEach((data) => {
        if (
          (this.type !== 8 && data.row.needEnv == 'true') ||
          (this.type === 8 && data.row.__needEnv)
        ) {
          let challWithEnv = {
            imageRef: data.row.imageId,
            name: data.row.name,
            flavorRef: data.row.flavorRef,
            chaId: data.row.chaId,
            vmCount: this.type === 2 ? undefined : 0,
            circumstance: this.type === 2 ? data.row.circumstance : ''
          }
          if (data.row.rangeId == this.selfRange.id) {
            challWithEnv.shootingRange = 1
          } else {
            challWithEnv.shootingRange = 2
          }
          challWithEnvList.push(challWithEnv)
        }
        let chall = {
          chaId: data.row.chaId,
          chaName: data.row.name,
          hidden: 0,
          data: data.row,
          circumstance: this.type === 2 && data.row.needEnv == 'true' ? data.row.circumstance : ''
        }
        if (data.row.rangeId == this.selfRange.id) {
          chall.shootingRange = 1
        } else {
          chall.shootingRange = 2
        }
        challList.push(chall)
      })
      this.challList.push(...challList)
      this.challWithEnvList.push(...challWithEnvList)
    },
    // 删除选中的题目
    removeQuestion(selection, row) {
      let chaIdList = []
      let removeChaList = []
      // 将选中的题目设置为未选中状态
      if (!row) {
        // 全选
        this.challsDataPage.forEach((ques) => {
          //
          ques._checked = false
          ques.__needEnv = false
          chaIdList.push(ques.chaId)
        })
      } else {
        let listQues = this.challsDataPage.filter((item) => item.chaId == row.chaId)
        if (listQues.length > 0) {
          listQues[0]._checked = false
          listQues[0].__needEnv = false
        }
        chaIdList.push(row.chaId)
      }
      // 拷贝两份数据做批量操作，最终赋值一次
      let challList = [...this.challList],
        challWithEnvList = [...this.challWithEnvList]
      chaIdList.forEach((id) => {
        let delChallIndex = challList.findIndex((item) => item.chaId === id)
        if (delChallIndex >= 0) challList.splice(delChallIndex, 1)
        let delChallIndexEnv = challWithEnvList.findIndex((items) => items.chaId === id)
        if (delChallIndexEnv >= 0) {
          removeChaList.push(...challWithEnvList.splice(delChallIndexEnv, 1))
        }
      })
      this.challList = challList
      if (this.type === 8) {
        // 遍历已选题目与被删除的题目，如果已选题目中存在与删除题目使用相同镜像的情况，将该题目重新放入需要部署环境的数组中
        removeChaList.forEach((item) => {
          for (let i = 0, length = challList.length; i < length; i++) {
            if (item.imageRef === challList[i].data.imageId) {
              this.challList[i].data.__needEnv = true
              challWithEnvList.push({
                imageRef: challList[i].data.imageId,
                name: challList[i].data.name,
                flavorRef: challList[i].data.flavorRef,
                chaId: challList[i].data.chaId,
                vmCount: this.type === 2 ? undefined : 0
              })
              this.challsDataPage.forEach((subItem) => {
                if (subItem.id === challList[i].data.id) {
                  this.$set(subItem, '__needEnv', true)
                }
              })
              return
            }
          }
        })
      }
      this.challWithEnvList = challWithEnvList
    },
    // 获取团队列表，级联查询团队下的所有用户，用于成员同名筛查
    getAllTeamlist(rangeId) {
      this.loadingTable = true
      let _this = this
      _this.teamListObj.rangeId = rangeId
      getGroupHasUsers(_this.teamListObj)
        .then(({ data }) => {
          if (data.code == 1) {
            _this.teamsDataPage = []
            // let teamsDataPage = [];
            if (data.data) {
              // 已选中的团队
              let selTeamIds = this.teamList.map((team) => team.id)
              _this.teamsDataPage = data.data.items.map((team) => {
                let params = team
                params._checked = selTeamIds.includes(params.id) // 查询的团队已被选中，让其处于选中状态
                let userNameList = []
                let userIdList = []
                team.userList.forEach((user) => {
                  userNameList.push(user.username)
                  userIdList.push(user.id)
                })
                params.userNameList = userNameList
                params.userList = userNameList.join(',')
                params.userIdList = userIdList
                params.userNum = userIdList.length
                params._disabled = userIdList.length === 0 ? true : false
                return params
                // teamsDataPage.push(params)
                // // 获取团队下的用户数据
                // await getExperGroupsUsers(team.id).then(data => {
                //     if (data.code == 1) {
                //         let userNameList = []
                //         let userIdList = []
                //         data.data.forEach(user => {
                //             userNameList.push(user.userName)
                //             userIdList.push(user.userId)
                //         })
                //     	params.userList = userNameList.join(',')
                //     	params.userIdList = userIdList
                //         params.userNum = data.data.length;
                // 		params._disabled = userIdList.length === 0 ? true : false
                //         teamsDataPage.push(params)
                //     }
                // });
              })
              // Promise.all(proArr).then(() => {
              // 	_this.teamsDataPage = teamsDataPage;
              // })
            }
            _this.teamsTotal = Number(data.data.total)
          } else {
            _this.teamsDataPage = []
            _this.teamsTotal = 0
            this.$Message.warning(message)
          }
        })
        .catch((error) => {
          this.$Message.error('获取团队异常')
        })
        .finally(() => {
          this.loadingTable = false
        })
    },
    // 指定分页大小查询当前页团队数据
    teamsChangeSize(page) {
      this.teamListObj.pageSize = page
      this.getAllTeamlist(this.rangeIdGroup)
    },
    // 查询指定页团队数据
    teamsPageNum(val) {
      this.teamListObj.pageIndex = val
      this.getAllTeamlist(this.rangeIdGroup)
    },
    // 查询首页团队列表
    queryTeamList() {
      this.teamListObj.pageIndex = 1
      this.getAllTeamlist(this.rangeIdGroup)
    },
    // 选中团队，并判断团队是否存在相同的成员
    selectTeam(selection, row) {
      let userIds = []
      let addTeamList = []
      if (!row) {
        // 全选
        let selTeamIds = this.teamList.map((team) => team.id) // 已选中的数据
        selection.forEach((team) => {
          if (!selTeamIds.includes(team.id)) {
            // 添加尚未选中的数据
            userIds.concat(team.userIdList)
            // 让添加的数据处于选中状态
            let listTeam = this.teamsDataPage.find((item) => item.id == team.id)
            if (listTeam) {
              listTeam._checked = true
            }
            addTeamList.push(team)
          }
        })
      } else {
        // 单选
        userIds = row.userIdList
        // 让添加的数据处于选中状态
        let listTeam = this.teamsDataPage.find((item) => item.id == row.id)
        if (listTeam) {
          listTeam._checked = true
        }
        addTeamList.push(row)
      }
      let allSelUserIds = [...this.teamList.map((team) => team.userIds).flat(), ...userIds]
      if (this.haveDuplicateMembers(allSelUserIds)) {
        this.showDuplicateNameTip = true
      } else {
        this.showDuplicateNameTip = false
      }
      let teamList = addTeamList.map((item) => {
        if (item.rangeId == this.selfRange.id) {
          return {
            id: item.id,
            name: item.name,
            addUserEnable: false,
            userIds: item.userIdList,
            userNameList: item.userNameList,
            _checked: true,
            shootingRange: 1
          }
        } else {
          return {
            id: item.id,
            name: item.name,
            addUserEnable: false,
            userIds: item.userIdList,
            userNameList: item.userNameList,
            _checked: true,
            shootingRange: 2
          }
        }
      })
      this.teamList.push(...teamList)
    },
    // 判断是否有重复的成员，去重后长度不一致，则存在相同成员
    haveDuplicateMembers(allSelUserIds) {
      return [...new Set(allSelUserIds)].length != allSelUserIds.length
    },
    // 删除选中的团队
    removeTeam(selection, row) {
      let teamIdList = []
      if (!row) {
        // 通过全选来删除团队
        this.teamsDataPage.forEach((team) => {
          team._checked = false
          teamIdList.push(team.id)
        })
      } else {
        // 删除单个团队
        let listTeam = this.teamsDataPage.filter((item) => item.id == row.id)
        if (listTeam.length > 0) {
          listTeam[0]._checked = false
        }
        teamIdList.push(row.id)
      }
      let teamList = [...this.teamList]
      teamIdList.forEach((id) => {
        // 删除tags数据
        let delteamIndex = teamList.findIndex((items) => items.id === id)
        if (delteamIndex >= 0) teamList.splice(delteamIndex, 1)
      })
      this.teamList = teamList
      // 判断是否存在相同的成员
      let allSelUserIds = [...this.teamList.map((team) => team.userIds).flat()]
      if (this.haveDuplicateMembers(allSelUserIds)) {
        this.showDuplicateNameTip = true
      } else {
        this.showDuplicateNameTip = false
      }
    },
    // 模态框隐藏时，重置相关数据
    visibleChange(flag) {
      if (!flag) {
        this.deploymentType = this.$options.data().deploymentType
        this.quickCreatForm = this.$options.data().quickCreatForm
        this.sceneOptions = this.$options.data().sceneOptions
        this.showDuplicateNameTip = false
        this.hasFlagServer = false
      } else {
        this.saveLoading = false
      }
      this.$nextTick(() => {
        this.noTeam = false
      })
    },
    handleBeforeChange(value, type) {
      return new Promise((resolve) => {
        if (
          this.onlineMode == 0 &&
          this.challWithEnvList.length > 0 &&
          ((type === 'vm' && !this.quickCreatForm.pmInEnable && this.quickCreatForm.vmInEnable) ||
            (type === 'pm' && this.quickCreatForm.pmInEnable && !this.quickCreatForm.vmInEnable))
        ) {
          this.$Message.info('实物接入和虚拟接入至少选择一个!')
        } else {
          resolve()
        }
      })
    },
    // 保存数据并快速构建夺旗赛、攻防赛，这里只做了前置条件判断，构建主体抽取成了一个方法
    saveQuickCreate() {
      let list = this.teamList,
        teamLength = list.length
      if (teamLength === 0) {
        this.$Message.info('请选择团队!')
        return
      }
      if ([1, 8].includes(this.type) && teamLength < 2) {
        this.$Message.info('请选择至少两只团队！')
        return
      }
      if (teamLength < this.quickCreatForm.spareEnvNum) {
        this.$Message.error('备用环境套数不能超过团队数!')
        return
      }
      if (this.showDuplicateNameTip) {
        this.$Message.info('选择的团队中存在相同成员，请修改团队配置')
        return
      }
      let retList = []
      list.forEach((team, index) => {
        for (let i = index + 1; i < teamLength; i++) {
          let teamName = team.name
          let nextTeamName = list[i].name
          if (teamName === nextTeamName) {
            retList.push(`"${teamName}"`)
          }
        }
      })
      if (retList.length) {
        this.$Message.info(`${[...new Set(retList)].join(',')}团队名重名!`)
        return
      }
      if (this.challList.length === 0) {
        this.$Message.info('请选择题目!')
        return
      }
      if (
        !this.quickCreatForm.vmInEnable &&
        !this.quickCreatForm.pmInEnable &&
        this.challWithEnvList.length > 0 &&
        this.onlineMode == 0
      ) {
        this.$Message.info('实物接入和虚拟接入至少选择一个!')
        return
      }
      this.quickCreatForm.batchDeploySize = parseInt(this.quickCreatForm.batchDeploySize)
      // 分批构建还需要检测可部署的虚拟机个数
      if (this.deploymentType) {
        if (this.maxScope === 0) {
          this.$Message.info('所选题目不需要环境，请关闭分批构建')
          return
        }
        if (
          this.quickCreatForm.batchDeploySize < 1 ||
          this.quickCreatForm.batchDeploySize > this.maxScope
        ) {
          this.$Message.info('批次大小设置有误')
          return
        }
      }
      // 快速构建
      this.saveQuickScene()
    },
    // 快速构建----保存场景，场景构建完毕后保存题目
    saveQuickScene() {
      this.$refs['quickCreatForm']
        .validate((valid) => {
          if (valid) {
            this.saveLoading = true
            let { id: contestId, name: contestName } = this.quickCreatPass
            let {
              spareEnvNum,
              batchDeploySize,
              vmInEnable,
              pmInEnable
            } = this.quickCreatForm
            // 处理团队数据
            let teams = this.teamList.map((team) => {
              return {
                ...team,
                players: team.userIds.map((userId, index) => ({
                  userId,
                  username: team.userNameList[index]
                }))
              }
            })
            // 判断输入的团队中是否有相同的名称
            let extension
            try {
              extension = JSON.parse(this.quickCreatPass.extension)
            } catch (error) {
              extension = {}
            }
            this.sceneOptions = {
              ...this.sceneOptions,
              rangeId: this.selfRange.id,
              contestId,
              contestName,
              contestPapers: this.challWithEnvList,
              spareEnvNum,
              vmInEnable,
              pmInEnable,
              needEnv:
                this.challWithEnvList.length > 0 || (this.type === 2 && this.envType === 1)
                  ? true
                  : false, //夺旗赛独享环境无论有没有选择有环境的题目都需要环境（topo）
              dataChannelEnable: true,
              vm_enable: false,
              teams,
              distributedType: extension.isDistributed == 1 ? 'distributed' : 'normal',
              batchDeploySize: this.deploymentType ? batchDeploySize : undefined, // 非分批部署模式不需要保存这个值
              userNum: 1, // 这个属性后端也不清楚是干嘛的，故维持现状，传参写死为1
              modeType: this.onlineMode,
              outsideGatewayIP: extension.outsideGatewayIP || '',
              onLineType: extension.onLineType,
              enableBatchDeploy: this.deploymentType,
              deployMode: extension.deployMode,
              publicSubnetId: extension.publicSubnetId
            }
            let sceneOptions = Object.assign({}, this.sceneOptions)
            if (this.type === 1) {
              // 攻防赛不需要传递这些参数，避免扰乱后端逻辑
              delete sceneOptions.rangeId
              delete sceneOptions.autoStandbyEnable
              delete sceneOptions.batchDeploySize
              delete sceneOptions.dataChannelEnable
              delete sceneOptions.enableBatchDeploy
              delete sceneOptions.matchMode
              delete sceneOptions.modeType
              delete sceneOptions.onLineType
              delete sceneOptions.outsideGatewayIP
              delete sceneOptions.userNum
              delete sceneOptions.vm_enable
              // 添加部署模式
              sceneOptions.flagServer = this.hasFlagServer
              sceneOptions.hwDeployMode = extension.deployMode === 2 ? 'route' : 'tunnel'
              sceneOptions.type = 'offense_and_defense' // 攻防赛类型需要转义
              if (this.vmTeamOrPerson === 'person') {
                sceneOptions.terminalEnable = true
                sceneOptions.noNeedProjectService = true
              }
            }
            if (this.type === 2) {
              let { ctfOnlineType, ipMode } = extension
              sceneOptions.type = 'capture_the_flag'
              if (this.ctfVpn) { //线上vpn
                sceneOptions.ctfMode = ipMode === 'oneTeamOneIp' ? 'vpn' : 'vpnAllTeam'
              }else if(this.onlineMode === 1){ //线上 域名或ip+端口模式
                sceneOptions.ctfOnlineType = ctfOnlineType
              }
              if (this.vmTeamOrPerson === 'person') {
                sceneOptions.terminalEnable = true
                sceneOptions.noNeedProjectService = true
              }
            }
            if (this.type === 8) {
              // 攻防赛Plus走的是线下夺旗赛的部署策略，只是需要修改type的类型
              sceneOptions.type = 'offense_and_defense_plus'
              sceneOptions.hwDeployMode = extension.deployMode === 2 ? 'route' : 'tunnel'
              if (this.vmTeamOrPerson === 'person') {
                sceneOptions.terminalEnable = true
                sceneOptions.noNeedProjectService = true
              }
            }
            if (this.type === 9) {
              // 运维赛同样走的是线下夺旗赛的部署策略，只是需要修改type的类型
              sceneOptions.type = 'operation_and_maintenance'
              sceneOptions.hwDeployMode = extension.deployMode === 2 ? 'route' : 'tunnel'
              if (this.vmTeamOrPerson === 'person') {
                sceneOptions.vmTeamOrPerson = 'person'
                sceneOptions.noNeedProjectService = true
              }
            }
            let api
            api = quickCreateContest
            if ([1, 2, 8].includes(this.type) && this.vmTeamOrPerson === 'person') {
              api = quickCreateContestMacth
            }
            api(sceneOptions)
              .then((data) => {
                if (data.code === 1) {
                  // 场景构建成功，保存题目数据
                  if (this.type === 2) {
                    this.saveCtfPaper(data.data.projectId, data.data.projectName)
                  } else {
                    this.saveAwdPaper(data.data.projectId, data.data.projectName)
                  }
                } else {
                  if (data.message) {
                    this.$Message.warning(data.message)
                  }
                  this.saveLoading = false
                }
              })
              .catch((error) => {
                this.$Message.error('快速构建异常')
                this.saveLoading = false
              })
          }
        })
        .catch((error) => {
          // console.log(error)
        })
    },
    // 攻防赛绑定题目与场景关系
    saveAwdPaper(projectId, projectName) {
      let params = this.challList.map((item) => {
        return {
          description: item.data.description, //描述
          externalIp: '', // 对外ip
          externalPort: '', // 对外端口
          name: item.data.name, //题目显示名称
          port: item.data.port,
          projectId: projectId,
          questionId: item.data.id, //题目id
          sceneId: this.quickCreatPass.id,
          score: item.data.score,
          type: 1,
          visibility: 0, //可见性：是否可见- 0.不可见 1可见
          flagPath: item.data.flagPath,
          servicePort: item.data.port,
          isNeedSubmitFlag: item.data.flagType === '2' ? '2' : String(item.data.submitFlag), // 是否需要提交flag    0：不需要（报告验证）    1：需要    2：checker
          isFixedFileFlag: String(item.data.flagType), // 是否固定文件  0：固定flag    1：静态flag
          flag: item.data.flagTxt,
          imageId: item.data.imageId,
          imageName: item.data.imageName,
          fileId: item.data.attachmentId,
          fileName: item.data.attachmentName,
          filePath: item.data.attachmentPath,
          isExistTips:
            item.data.attachmentName && String(item.data.attachmentName).trim() !== '' ? 1 : 0,
          defensivePort: item.data.defensivePort
        }
      })
      batchAddTarget(params).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        modifyScene(this.quickCreatPass.id, {
          id: this.quickCreatPass.id,
          projectId,
          projectName
        }).then((data) => {
          if (data.code !== 1) {
            this.$Message.warning(data.message)
            return
          } else {
            this.showCtfQuicklyConfig = false
            if (this.type === 9) {
              this.$Message.success('快速构建运维赛成功')
            } else {
              this.$Message.success(`快速构建攻防赛${this.type === 8 ? 'Plus' : ''}成功`) // 攻防赛plus需要提示创建攻防赛plus成功
            }
            this.$emit('getCompetList')
          }
        })
      })
    },
    // 保存快速构建----题目
    saveCtfPaper(projectId, projectName) {
      let { id: sceneId } = this.quickCreatPass
      let api, params
      if (this.ctfVpn) {
        let paperIns = this.challList.map((cha) => {
          return {
            id: cha.chaId,
            circumstance: cha.circumstance
          }
        })
        api = saveCtfPaperNew
        params = { paperIns, sceneId }
      } else {
        let ids = this.challList.map((cha) => cha.chaId)
        api = saveCtfPaper
        params = { ids, sceneId }
      }
      api(params)
        .then((data) => {
          if (data.code === 1) {
            // 题目保存成功，ctf快速构建成功
            // 分批构建，需要额外修改场景的扩展字段与绑定工程关系
            let param = {
              id: this.quickCreatPass.id,
              projectId: projectId,
              projectName: projectName
            }
            if (this.deploymentType) {
              let extension
              try {
                extension = JSON.parse(this.quickCreatPass.extension)
              } catch (e) {
                extension = {}
              }
              extension.deploymentType = true
              extension.batchDeploySize = this.quickCreatForm.batchDeploySize
              extension.runningVmNum = 1
              this.quickCreatPass.extension = JSON.stringify(extension)
              this.quickCreatPass.projectId = projectId
              this.quickCreatPass.projectName = projectName
              param.extension = JSON.stringify(extension)
            }
            this.modifyScene(this.quickCreatPass.id, param)
          } else {
            if (data.message) {
              this.$Message.warning(data.message)
            }
            this.saveLoading = false
          }
        })
        .catch(() => {
          this.$Message.error('保存题目异常')
          this.saveLoading = false
        })
    },
    modifyScene(id, param) {
      modifyScene(id, param)
        .then((data) => {
          if (data.code !== 1) {
            // 修改成功后开始快速构建
            this.$Message.warning(data.message)
          } else {
            this.$Message.info('快速构建夺旗赛成功')
            this.showCtfQuicklyConfig = false
            this.$emit('getCompetList')
          }
        })
        .catch((error) => {
          this.$Message.error('修改场景失败，请检查网络设置')
        })
    },
    // 关闭模态框
    closeModal() {
      this.showCtfQuicklyConfig = false
    }
  }
}
</script>

<style scoped>
.error-text {
  color: #ed4014;
}
.text-left {
  text-align: left;
}
.text-left >>> .ivu-poptip-popper {
  width: 330px;
  max-width: 330px;
}
.mtb {
  margin: 16px 0;
}
.mr {
  margin-right: 16px;
}
.sel-team,
.sel-ques {
  width: 100%;
}
.sel-team-tag,
.sel-ques-tag {
  display: flex;
  max-width: 100%;
  width: max-content;
  align-items: center;
  float: left;
}
.sel-team-tag >>> .ivu-tag-text,
.sel-ques-tag >>> .ivu-tag-text {
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: inline-block;
}
.sel-team-tag >>> .ivu-tag-dot-inner,
.sel-ques-tag >>> .ivu-tag-dot-inner {
  flex-shrink: 0;
  top: 0;
}
.deployment-switch {
  width: 80px;
}
.deployment-switch.ivu-switch-checked:after {
  left: 59px;
}
.search-criteria-row {
  height: 32px;
}
</style>
<style>
#envNum .ivu-form-item-label {
  text-align: left;
  padding-right: 2px;
}
.ivu-tooltip-inner {
  word-break: break-all;
}
</style>
